import React, { useState, useRef, useEffect } from "react";
import { Search } from "react-vant";
import { Swiper, Image, NavBar } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Button, SearchBar, Space, Toast, Input } from "antd-mobile";
import { SearchBarRef } from "antd-mobile/es/components/search-bar";
import { DeleteOutline } from "antd-mobile-icons";
import { debounce } from "lodash";
import { ShareO } from "@react-vant/icons";
import axios from "axios";
import "./index.css";

const index: React.FC = () => {
  let navigate = useNavigate();
  const searchRef = useRef<SearchBarRef>(null);
  const [searchList, setSearchList] = useState<any>([]);
  let [historyList, setHistoryList] = useState<any>(
    JSON.parse(localStorage.getItem("historyList")!) || []
  );
  const shopsearch = debounce((val: any) => {
    axios
      .get("/api/search", {
        params: {
          val: val,
        },
      })
      .then((resp) => {
        setSearchList(resp.data.items);
      });
    if (val !== "") {
      historyList.unshift(val);
      setHistoryList([...new Set(historyList)]);
      localStorage.setItem(
        "historyList",
        JSON.stringify([...new Set(historyList)])
      );
    }
  }, 500);
  const del = () => {
    historyList = [];
    setHistoryList([...new Set(historyList)]);
    localStorage.setItem(
      "historyList",
      JSON.stringify([...new Set(historyList)])
    );
  };

  return (
    <div>
      <div className="searchtop">
        <NavBar
          title="搜索"
          onClickLeft={() => navigate(-1)}
          rightText={<ShareO fontSize={20} />}
        />
        <SearchBar
          ref={searchRef}
          placeholder="请输入内容"
          showCancelButton
          onSearch={(val) => shopsearch(val)}
          onFocus={() => {
            console.log("获得焦点");
          }}
          onBlur={() => {
            console.log("失去焦点");
          }}
          onCancel={() => {
            console.log("取消搜索");
          }}
        />
      </div>
      <div className="historyList">
        <span className="del" onClick={() => del()}>
          <DeleteOutline />
        </span>
        历史记录:
        {historyList.length > 0 &&
          historyList.map((item, index) => <div>{item}</div>)}
      </div>
      <div className="searchtopbtn">
        {searchList.length > 0 &&
          searchList.map((item: any, index: any) => (
            <div key={index}>
              <div>
                <div>
                  <img src={item.img} />
                </div>
                <div>{item.title}</div>
                <div>{item.prcic}</div>
                <div>{item.desc}</div>
              </div>
            </div>
          ))}
      </div>
    </div>
  );
};

export default index;
